import Vue from 'vue'
import VueRouter from 'vue-router'
import cookie from '../utils/cookies'
Vue.use(VueRouter)

  const routes = [
  {
    path: '/home',
    name: 'Home',
    component: () => import('../views/Home/index'),
    meta: {
      title: '首页'
    }
  },
  {
    path: '/classfy',
    name: 'Classfy',
    component: () => import('../views/Classfy/index'),
    meta: {
      title: '分类'
    },
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login/index'),
    meta: {
      title: '验证手机'
    }
  },
  {
    path: '/car',
    name: 'Car',
    component: () => import('../views/Car/index'),
    meta: {
      title: '购物车',
      isAuth: true
    }
  },
  {
    path: '/mine',
    name: 'Mine',
    component: () => import('../views/Mine/index'),
    meta: {
      title: '我的',
      isAuth: true
    }
  },
  {
    path: '/detail/:id',
    name: 'Detail',
    component: () => import('../views/Detail/index'),
    meta: {
      title: '详情页'
    }
  },
  {
    path: '/search',
    name: 'Search',
    component: () => import('../views/Search/index'),
    meta: {
      title: '搜索页'
    }
  },
  {
    path: '/maptext',
    name: 'mapText',
    component: () => import('../views/mapText/index'),
    meta: {
      title: '地图'
    }
  },
  {
    path: '/',
    redirect:'/home'
  },

]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach((to, from, next) => {
  if (to.meta.isAuth) {
    const token = cookie.get('token');
    if(token) {
      next()
    } else {
      next({
        path: '/login',
        query: {
          callbackUrl: to.path
        }
      })
    }
    console.log(token);
  } else {
    next()
  }
})
router.afterEach((to, from) => {
  document.title = to.meta.title
})
export default router
